package com.cuhk.gulimall.product.utils.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Arrays;

public class RedisOperations {
    @Autowired
    private static RedisTemplate redisTemplate;

    public static final String LOCK_SCRIPT = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1" +
            "then redis.call('expire', KEYS[1], ARGV[2]) return 1" +
            "else return 0 end";

    public static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] " +
            "then return redis.call('del', KEYS[1])" +
            "else return 0 end";

    public static int unlock(String key, String uuid) {
        Integer res = (Integer) redisTemplate.execute(new DefaultRedisScript<>(UNLOCK_SCRIPT, Integer.class), Arrays.asList(key), uuid);
        return res;
    }

    public static int lock(String key, String uuid, long timeout) {
        Integer res = (Integer) redisTemplate.execute(new DefaultRedisScript<>(LOCK_SCRIPT, Integer.class), Arrays.asList(key), Arrays.asList(uuid, timeout));
        return res;
    }

}
